package com.myown.spring.bean;

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模拟spring {@link ClassPathXmlApplicationContext}
 *
 * @author lincky
 * @version v1.0.0
 * @time 2017.03.24 16:28
 */
public class MyClassPathXmlApplicationContext {

    private Map<String, Object> beans = new HashMap<>();

    private List<Bean> xmlBeans = new ArrayList<>();

    public MyClassPathXmlApplicationContext(String xml) {
        //第一步，解析spring配置文件
        readXml(xml);
        //第二步，通过反射，实例化所有注入bean
        initBeans();
    }

    /**
     * 将xml中配置的bean装载到bean表中
     */
    private void initBeans() {
        for (Bean bean : xmlBeans) {
            if (!StringUtils.isEmpty(bean.getName())) {
                try {
                    beans.put(bean.getId(), Class.forName(bean.getName()).newInstance());
                } catch (InstantiationException |
                        IllegalAccessException |
                        ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取xml中的bean
     * @param xml xml文件路径
     */
    private void readXml(String xml) {
        SAXReader reader = new SAXReader();
        URL xmlpath = this.getClass().getClassLoader().getResource(xml);
        System.out.println(xmlpath);
        Map<String, String> xmlMap = new HashMap<>();
        try {
            xmlMap.put("ns", "http://www.springframework.org/schema/beans");
            Document document = reader.read(xmlpath);
            XPath xPath = document.createXPath("//ns:beans//ns:bean");
            xPath.setNamespaceURIs(xmlMap);
            @SuppressWarnings("unchecked")
            List<Element> elements = xPath.selectNodes(document);
            for(Element element : elements) {
                String id = element.attributeValue("id");
                String clazz = element.attributeValue("class");
                xmlBeans.add(new Bean(id, clazz));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public Object getBean(String id) {
        return beans.get(id);
    }

}
